package lex.title;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;

public class ToggleButton extends JButton
{
	private Image[] images = null;
	private int state = 0;
	//============================
	private Dimension size = null;

	public ToggleButton( Image ... imgs )
	{
		super();
		this.images = imgs;
		//=============================		
		this.setText( null );
		this.setBorderPainted( false );
		this.setContentAreaFilled( false );
		this.setFocusPainted( false );
		this.setFocusable( false );
		this.setOpaque( false );
		this.setRolloverEnabled( true );
		//=================================
		this.setSize( getPreferredSize() );
		this.addActionListener( new ActionListener(){
			public void actionPerformed( ActionEvent e )
			{
				state++;
				if( state >= images.length )
					state = 0;
				repaint();
			}
		} );
	}
	
	public void setImageIndex( int index )
	{
		this.state = index;
	}

	public Dimension getMinimumSize()
	{
		return this.getPreferredSize();
	}

	public Dimension getPreferredSize()
	{
		if( null == size )
		{
			int h = 1, w = 1;
			for( Image img : images )
			{
				int ih = img.getHeight( this );
				int iw = img.getWidth( this );
				if( h < ih )
					h = ih;
				if( w < iw )
					w = iw;
			}
			size = new Dimension( w, h );
		}
		return new Dimension( size );
	}

	public void paintComponent( Graphics g )
	{
		Image img = images[ state ];
		g.drawImage( img, 0, 0, this );
	}
}
